﻿using NewProject.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;


namespace NewProject.Controllers
{
    public class DataContextController : Controller
    {
        // GET: DataContext
        DataContext db = new DataContext();
        public ActionResult Index()
        {
            ViewData["reviews"] = db.Reviews.ToList().OrderByDescending(x => x.ReviewDate);
            ViewData["message"] = "Showing All Posts";
            return View(db.Posts.ToList().OrderBy(x=>x.Title));
            
        }

        // GET: DataContext/Details/5
        public ActionResult Details(int id)
        {
            ViewData["reviews"] = db.Reviews.ToList().OrderByDescending(x => x.ReviewDate);
            return View();
        }

        // GET: DataContext/Create
        [Authorize]
        public ActionResult Create()
        {
            ViewData["reviews"] = db.Reviews.ToList().OrderByDescending(x => x.ReviewDate);
            ViewData["message"] = "Creating A New Post";
            return View();
        }

        // POST: DataContext/Create
       
        [HttpPost]
        public ActionResult Create(Post post)
        {
            ViewData["message"] = "Creating A New Post";
            ViewData["reviews"] = db.Reviews.ToList().OrderByDescending(x => x.ReviewDate);
            try
            {
                // TODO: Add insert logic here
               // post.UserID = User.Identity.GetUserId();

                post.UserName = User.Identity.GetUserName().ToString();
                post.PostDate = DateTime.Now;
                db.Posts.Add(post);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            catch
            {
                return RedirectToAction("Index");
            }
        }

        // GET: DataContext/Edit/5
        public ActionResult Edit(int id)
        {
            ViewData["message"] = "Editing A Post";
            ViewData["reviews"] = db.Reviews.ToList().OrderByDescending(x => x.ReviewDate);
            return View();
        }

        // POST: DataContext/Edit/5
        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            ViewData["reviews"] = db.Reviews.ToList().OrderByDescending(x => x.ReviewDate);
            ViewData["message"] = "Editing A Post";
            try
            {
                // TODO: Add update logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        // GET: DataContext/Delete/5

        public ActionResult DeleteReview(int id)

        {
            ViewData["reviews"] = db.Reviews.ToList().OrderByDescending(x => x.ReviewDate);
            Review review = db.Reviews.Find(id);
            if ((User.Identity.GetUserName() == review.Post.UserName)
                || (User.Identity.GetUserName() ==review.UserName))
            {
                db.Reviews.Remove(review);
                db.SaveChanges();
            }
            return RedirectToAction("Index");
        }

        public ActionResult Delete(int id)
        {
            ViewData["message"] = "Showing All Posts";
            ViewData["reviews"] = db.Reviews.ToList().OrderByDescending(x => x.ReviewDate);
            Post post = db.Posts.Find(id);
            if (User.Identity.GetUserName() == post.UserName)
            {
                List <Review> reviews = post.Reviews.ToList();

                foreach (var item in reviews)
                {
                    db.Reviews.Remove(item);
                    db.SaveChanges();
                }
                db.Posts.Remove(post);
                db.SaveChanges();
                
            }
            return RedirectToAction("Index");
        }

        // POST: DataContext/Delete/5
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            ViewData["reviews"] = db.Reviews.ToList();
            try
            {
                // TODO: Add delete logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        public ActionResult Search(string search, string searchType)
        {
            ViewData["reviews"] = db.Reviews.ToList().OrderByDescending(x => x.ReviewDate);
            if (searchType == null)
            {
                var songs1 = db.Posts.Where(s => s.Title.Contains(search)).ToList();
                var songs2 = db.Posts.Where(s => s.Album.Contains(search)).ToList();
                var songs3 = db.Posts.Where(s => s.UserName.Contains(search)).ToList();
                var songs4 = db.Posts.Where(s => s.PostText.Contains(search)).ToList();
                // var songs6 = db.Songs.Where(s => (s.ReleseDate.Date.Year).Equals(Convert.ToInt32(search))).ToList();
                var data = songs1.Union(songs2).ToList();
                data = data.Union(songs3).ToList();
                data = data.Union(songs4).ToList();
                //   data = data.Union(songs6).ToList();
                ViewData["message"] = "Search Result for : "+search;
                return View("Index", data);
            }
            else if (searchType.Equals("Title"))
            {
                ViewData["message"] = "Search Result for Title: " + search;
                var songs1 = db.Posts.Where(s => s.Title.Contains(search)).ToList();
                return View("Index", songs1);
            }
            else if (searchType.Equals("Album"))
            {
                ViewData["message"] = "Search Result for Album: " + search;
                var songs2 = db.Posts.Where(s => s.Album.Contains(search)).ToList();
                return View("Index", songs2);
            }

            else if (searchType.Equals("Artist"))
            {
                ViewData["message"] = "Search Result for User: " + search;
                var songs3 = db.Posts.Where(s => s.UserName.Contains(search)).ToList();
                return View("Index", songs3);
            }

            else if (searchType.Equals("UserName"))
            {
                ViewData["message"] = "Search Result for UserName : " + search;
                var songs4 = db.Posts.Where(s => s.UserName.Contains(search)).ToList();
                return View("Index", songs4);
            }
            else if (searchType.Equals("Genre"))
            {
                ViewData["message"] = "Search Result for Genre : " + search;
                var songs5 = db.Posts.Where(s => s.PostText.Contains(search)).ToList();
                return View("Index", songs5);
            }

            else if (searchType.Equals("Year"))
            {
                ViewData["message"] = "Search Result for Year : " + search;
                var songs6 = db.Posts.Where(s => s.PostDate.Date.Year.ToString().Equals(search));
                return View("Index", songs6);
            }

            else if (searchType.Equals("PostID"))
            {
                ViewData["message"] = "Displaying Reviewed Post : ";
                var song7 = db.Posts.Find(Convert.ToInt32(search));
                List<Post> song8 = new List<Post>();
                song8.Add(song7);
                return View("Index", song8);
            }
            else  return RedirectToAction("Index");
        }

        public List<Review> SearchReviews(int id){
            return (db.Reviews.Where(m=>m.PostID==id).ToList());
        }
        public JsonResult AddRating(int id, int rate)
        {
           
            ViewData["reviews"] = db.Reviews.ToList().OrderByDescending(x => x.ReviewDate);
            // access your database here and update/insert the vote
            Post post = db.Posts.Find(id);
            
            int success=6;

            if (post != null)
            {
                List<Review> allReviews = SearchReviews(id);
                var myReview = allReviews.Where(s => s.UserName == User.Identity.GetUserName()).ToList();
                
                var maxID = db.Reviews.OrderByDescending(s => s.ReviewID).ToList();
                int max = 1;
                if ((maxID == null) || (maxID.Count <= 0))
                {
                    max = 100;
                }
                else
                {

                    var m2 = maxID[0];
                    max = m2.ReviewID;

                }

                if(myReview.Count>0){
                    success = 1;
                    rate = myReview[0].Rating;
                }

                else  
                {
                    try
                    { 
                        Review review = new Review();
                        review.ReviewID = max + 1;
                        review.Rating = rate;
                        review.PostID = id;
                        review.UserName = User.Identity.GetUserName().ToString();
                        review.Post = db.Posts.Find(id);
                        review.ReviewDate = DateTime.Now;
                        db.Reviews.Add(review);
                        db.SaveChanges();
                        success = 0;
                    }
                    catch
                    {
                        success = 2;
                    }

                }
                
               
            }
            return Json(new { success = success, pid = post.PostID, rate = rate }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult AddReview(int id, string comment)
        {
            ViewData["reviews"] = db.Reviews.ToList().OrderByDescending(x => x.ReviewDate);
            // access your database here and update/insert the vote
            int success = 6;

            if (String.IsNullOrEmpty(comment.Trim()))
            {
                success = 1;
            }
            else
            {
                Post post = db.Posts.Find(id);
                if (post != null)
                {
                    List<Review> allReviews = SearchReviews(id);
                    var myReviews = allReviews.Where(s => s.UserName == User.Identity.GetUserName()).ToList();
                  
                    if (myReviews.Count<=0)
                    {
                        success = 2;
                    }

                    else
                    {
                        var myReview = myReviews[0];
                        if (String.IsNullOrEmpty(myReview.ReviewText))
                        {

                            try
                            {
                                myReview.ReviewText = comment.Trim();
                                db.SaveChanges();
                                success = 0;
                            }
                            catch
                            {
                                success = 6;
                            }
                        }
                        else
                        {
                            success = 3;
                        }

                    }
                }
            }
            
        

           
            return Json(new { success = success, pid = id}, JsonRequestBehavior.AllowGet);
        }


    }
}
